package com.tusuo.stds.ui.bindnew;

import android.content.Context;
import android.os.Handler;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.ui.login.ThirdLoginUserInfo;
import com.tusuo.stds.util.IntentUtils;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @author J.Huang
 * @version 1.0
 *
 */

@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(BindNewPresenter.class)
class BindNewPresenter extends MvpBasePresenter<BindNewView> {

    @Inject
    ApiHelper mApiHelper;

    private Context mContext;
    private String mErrMsgServer;

    private Subscriber<ApiResult> mGetCaptchaSubscriber = null;
    private Subscriber<ApiResult> mBindNewSubscriber = null;

    private Subscription mSubscriptionUpdateCountdown;
    private Handler mHandlerShowErrMsg;

    private boolean mIsWaiting;

    private ThirdLoginUserInfo mThirdLoginUserInfo;

    BindNewPresenter(Context context) {
        mContext = context;
        mHandlerShowErrMsg = new Handler();
        mIsWaiting = false;
        mErrMsgServer = mContext.getResources().getString(R.string.err_msg_server);

        Injector.initBindNewPresenterComponent().inject(this);
    }

    @Override
    public void detachView(boolean retainInstance) {
        if (mHandlerShowErrMsg != null) {
            mHandlerShowErrMsg.removeCallbacksAndMessages(null);
        }
        if (mSubscriptionUpdateCountdown != null) {
            mSubscriptionUpdateCountdown.unsubscribe();
            mSubscriptionUpdateCountdown = null;
        }
        if (mGetCaptchaSubscriber != null) {
            mGetCaptchaSubscriber.unsubscribe();
            mGetCaptchaSubscriber = null;
        }
        if (mBindNewSubscriber != null) {
            mBindNewSubscriber.unsubscribe();
            mBindNewSubscriber = null;
        }
        super.detachView(retainInstance);
    }

    private Runnable showSloganRunnable = new Runnable() {
        @Override
        public void run() {
            if (getView() != null) {
                getView().showSlogan();
            }
        }
    };

    void showErrMsg(String text) {
        if (getView() != null) {
            getView().showErrMsg(text);
            mHandlerShowErrMsg.postDelayed(showSloganRunnable, 3000);
        }
    }

    void getCaptcha(String mobileNo) {
        mGetCaptchaSubscriber = new GetCaptchaSubscriber();
        mApiHelper.getCaptcha(mGetCaptchaSubscriber, mobileNo);

        if (getView() != null) {
            mSubscriptionUpdateCountdown = updateCountdown()
                    .doOnSubscribe(new Action0() {
                        @Override
                        public void call() {
                            getView().setCaptchaBtnEnabled(false);
                            mIsWaiting = true;
                        }
                    })
                    .subscribe(new Subscriber<Integer>() {
                        @Override
                        public void onCompleted() {
                            getView().setCaptchaBtnText(mContext.getString(R.string.btn_captcha));
                            getView().setCaptchaBtnEnabled(true);
                            mIsWaiting = false;
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(Integer integer) {
                            getView().setCaptchaBtnText(mContext.getString(R.string.btn_wait_captcha, integer));
                        }
                    });
        }
    }

    private Observable<Integer> updateCountdown() {
        final int countTime = 60;

        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime+1);
    }

    boolean canGoBack() {
        return !mIsWaiting;
    }



    void bindNew(String mobileNo, String password, String captcha,ThirdLoginUserInfo mThirdLoginUserInfo) {
        mBindNewSubscriber = new BindNewSubscriber(mThirdLoginUserInfo);
        mApiHelper.bindNew(mBindNewSubscriber, mobileNo, password, captcha,
                mThirdLoginUserInfo.openId,
                mThirdLoginUserInfo.platForm,
                mThirdLoginUserInfo.accessToken,
                mThirdLoginUserInfo.nickName,
                mThirdLoginUserInfo.userIcon);

    }

    private class GetCaptchaSubscriber extends Subscriber<ApiResult> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            showErrMsg(mErrMsgServer);
        }

        @Override
        public void onNext(ApiResult result) {
            if (!result.checkState(mContext)) {
                showErrMsg(result.ErrorMessage);
            }
        }
    }

    private class BindNewSubscriber extends Subscriber<ApiResult> {

        private ThirdLoginUserInfo mThirdLoginUserInfo;

        public BindNewSubscriber(ThirdLoginUserInfo mThirdLoginUserInfo) {
            this.mThirdLoginUserInfo = mThirdLoginUserInfo;
        }

        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            showErrMsg(mErrMsgServer);
        }

        @Override
        public void onNext(ApiResult result) {
            if (result.checkState(mContext)) {
                IntentUtils.toBindNewMainActivity(mContext,mThirdLoginUserInfo,true);
            } else {
                showErrMsg(result.ErrorMessage);
            }
        }
    }
}
